import { BaseService, PageInfo } from "#/types";
import { Application } from "express";
/**
 * 基础增删改查Controller
 * @param app
 * @param url
 * @param service
 */
export function createBaseController<T extends BaseService<any>>(
  app: Application,
  url: string,
  service: T
) {
  app.get(url + "/list", async (req, res) => {
    res.send(await service.queryList(req.query as any));
  });
  app.post(url, async (req, res) => {
    res.send(await service.insert(req.body));
  });
  app.delete(url, async (req, res) => {
    res.send(await service.deleteById(req.query.id as string));
  });
  app.put(url, async (req, res) => {
    res.send(await service.update(req.body));
  });
}

/**
 * 规范化分页查询参数
 *
 * 将原始分页参数转换为标准格式，确保page和pageSize为数字类型
 *
 * @param pageInfo 原始分页参数对象
 * @returns 规范化后的分页参数对象
 *
 */
export function normalizePaginationParams(pageInfo: PageInfo): PageInfo {
  const page = Number(pageInfo.page);
  const pageSize = Number(pageInfo.pageSize);

  return {
    ...pageInfo,
    page,
    pageSize,
  };
}
